package com.yycx.base.provider.handler;

import com.yycx.common.constants.CommonConstants;
import com.yycx.common.base.entity.EntityMap;
import com.yycx.common.mybatis.interceptor.PageInterceptor;
import com.yycx.common.mybatis.model.PageParams;
import com.yycx.common.mybatis.query.CriteriaQuery;
import com.yycx.common.security.OpenHelper;
import com.yycx.common.base.utils.FlymeUtils;
import com.yycx.common.utils.ConvertUtils;
import com.yycx.module.admin.client.entity.BaseRole;
import com.yycx.module.admin.client.entity.BaseUser;
import com.yycx.module.admin.provider.service.BaseRoleService;
import com.yycx.module.system.client.entity.SysCompany;
import com.yycx.module.system.client.entity.SysOrganization;
import com.yycx.module.system.provider.service.SysCompanyService;
import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * 用户列表扩展(加入机构ID)
 *
 * @author zyf
 */
@Component
@AllArgsConstructor
public class AdminUserPageListHandler implements PageInterceptor<BaseUser> {

    private final SysCompanyService companyService;
    private final BaseRoleService roleService;

    @Override
    public void prepare(CriteriaQuery cq, PageParams pageParams, EntityMap params) {
        cq.select(BaseUser.class, "*");
        cq.select(SysOrganization.class, "organizationName");
        cq.select(SysCompany.class, "companyName");
        cq.eq(SysCompany.class,"companyId");
        Long companyId = OpenHelper.getCompanyId();
        Integer superAdmin = OpenHelper.getUser().getSuperAdmin();
        if (CommonConstants.INT_1.equals(superAdmin)) {
            //如果是超级管理员
            cq.eq(BaseUser.class, "organizationId");
        } else {
            SysCompany company = companyService.getById(companyId);
            if (FlymeUtils.isNotEmpty(company)) {
                cq.eq(BaseUser.class, "organizationId", company.getOrganizationId());
            }
        }
        cq.createJoin(SysOrganization.class);
        cq.createJoin(SysCompany.class);

    }

    @Override
    public void complete(CriteriaQuery<BaseUser> cq, List<EntityMap> result, EntityMap extra) {
        if (FlymeUtils.isNotEmpty(result)) {
            for (EntityMap entityMap : result) {
                Long userId = entityMap.getLong("userId");
                List<String> roleNames = roleService.selectRoleNamesByUserId(userId);
                if (FlymeUtils.isNotEmpty(roleNames)) {
                    entityMap.put("roleNames", ConvertUtils.listToString(roleNames));
                }
            }
        }
    }
}
